package cn.bitkit.tools.file;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringJoiner;

/**
 * 不支持复杂转义
 */
public class CsvUtil {

    public static List<List<String>> readFile(String file){
        return readText(FileUtil.readAsString(file));
    }

    public static List<List<String>> readText(String text){
        List<String> lineList = Arrays.asList(text.split("\n"));
        List<List<String>> list = new ArrayList<>();
        lineList.forEach(e -> {
            list.add(readLine(e));
        });
        return list;
    }

    public static List<String> readLine(String line){
        List<String> list = new ArrayList<>();
        String[] arr = line.split(",");
        boolean findEnd = false;
        StringBuilder ss = null;
        for(String s : arr){
            if(findEnd){
                ss.append(",").append(s);
                if(s.endsWith("\"")){
                    list.add(ss.toString());
                    findEnd = false;
                    ss = null;
                }
                continue;
            }
            if(s.startsWith("\"")){
                findEnd = true;
                ss = new StringBuilder(s);
                continue;
            }
            list.add(s);
        }
        if(ss != null){
            list.add(ss.toString());
        }
        for(int i=0; i<list.size(); i++){
            String data = list.get(i);
            if(data.startsWith("\"")){
                data = data.substring(1);
            }
            if(data.endsWith("\"")){
                data = data.substring(0, data.length()-1);
            }
            data = data.replaceAll("\"\"", "\"");
            list.set(i, data);
        }
        return list;
    }

    public static String asLine(String... text){
        StringJoiner joiner = new StringJoiner("\",\"", "\"", "\"");
        for(String s : text){
            joiner.add(s);
        }
        return joiner.toString();
    }

}
